<?php

namespace App\Http\Controllers;

use App\Models\Member\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\ValidationException;

class UserController extends Controller
{
    public function __construct()
    {
        $this->middleware('guest');
    }

    public function login(Request $request)
    {
        $res=['title'=>'登录'];
        return view('user.login',['res'=>$res]);
    }

    public function dologin(Request $request)
    {
        $request->old('phone');
        $userModel = new User;
        $post = $userModel->check($request,'login');
        $user = $userModel->where('phone', $post['phone'])->first();
        if($user){
            if(Hash::check($post['password'],$user['password'])){
                Auth::login($user);
                return redirect('/my');
            }else{
                throw ValidationException::withMessages([
                    'password' =>'密码错误',
                ]);
            }
        }else{
            throw ValidationException::withMessages([
                'phone' =>'手机号码不存在',
            ]);
        }
    }

    public function register(Request $request)
    {
        $res=['title'=>'注册'];
        return view('user.register',['res'=>$res]);
    }

    public function doregister(Request $request)
    {
        $request->old('phone');
        $userModel = new User;
        $post = $userModel->check($request,'register');
        $user = $userModel->register($post);
        Auth::login($user);
        return redirect('/login');
    }

    public function forget(Request $request)
    {
        $res=['title'=>'忘记密码'];
        $res['user']=Auth::user();
        return view('user.forget',['res'=>$res]);
    }

    public function doforget(Request $request)
    {
        return redirect('/');
    }



}
